<template>
  <div class="login-container">
    <!-- 登录表单 -->
    <el-form v-if="!showRecover" ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" autocomplete="on" label-position="left">
      <div class="title-container">
        <h3 class="title">平台管理</h3>
        <p>亿星本地化生活平台</p>
      </div>

      <el-form-item prop="name">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="name"
          v-model="loginForm.name"
          placeholder="用户名"
          name="name"
          type="text"
          tabindex="1"
          autocomplete="on"
        />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          ref="password"
          v-model="loginForm.password"
          type="password"
          placeholder="密码"
          name="password"
          tabindex="2"
          autocomplete="on"
          show-password
          @keyup.native="checkCapslock"
        />
      </el-form-item>

      <div class="img-code">
        <el-form-item prop="verifyCode">
          <span class="svg-container">
            <svg-icon icon-class="verifyCode" />
          </span>
          <el-input
            ref="verifyCode"
            v-model="loginForm.verifyCode"
            placeholder="图形验证码"
            name="verifyCode"
            type="text"
            tabindex="3"
            autocomplete="on"
          />
        </el-form-item>
        <img v-if="fcode!=''" @click="refreshCode" class="verifyCode-img" :src="fcode" />
      </div>

      <el-button type="primary" style="width:100%;margin-bottom:20px;" @click.native.prevent="handleLogin">登录</el-button>
      <div class="tips">
        <span style="float: right;" @click="showRecover = true">找回密码</span>
      </div>
    </el-form>

    <!-- 找回密码表单 -->
    <el-form v-else ref="recoverForm" :model="recoverForm" :rules="recoverRules" class="login-form" autocomplete="on" label-position="left">
      <div class="title-container">
        <h3 class="title">找回密码</h3>
      </div>

      <el-form-item prop="phone">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="phone"
          v-model="recoverForm.phone"
          placeholder="请输入手机号"
          name="phone"
          type="text"
          tabindex="1"
          autocomplete="on"
        />
      </el-form-item>

      <el-form-item prop="code">
        <span class="svg-container">
          <svg-icon icon-class="verifyCode" />
        </span>
        <el-input
          ref="code"
          v-model="recoverForm.code"
          placeholder="验证码"
          name="code"
          type="text"
          tabindex="2"
          autocomplete="on"
        />
        <el-button 
          class="send-code-btn" 
          :disabled="countdown > 0" 
          @click="sendSmsCode"
        >
          {{ countdown > 0 ? `${countdown}s后重新发送` : '获取验证码' }}
        </el-button>
      </el-form-item>

      <el-form-item prop="newPassword">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          ref="newPassword"
          v-model="recoverForm.newPassword"
          type="password"
          placeholder="新密码"
          name="newPassword"
          tabindex="3"
          autocomplete="off"
          show-password
        />
      </el-form-item>

      <el-form-item prop="confirmPassword">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          ref="confirmPassword"
          v-model="recoverForm.confirmPassword"
          type="password"
          placeholder="确认新密码"
          name="confirmPassword"
          tabindex="4"
          autocomplete="off"
          show-password
        />
      </el-form-item>

      <el-button type="primary" style="width:100%;margin-bottom:20px;" @click.native.prevent="handleRecover">确定</el-button>
      <el-button style="width:100%;margin-left:0;" @click.native.prevent="showRecover = false">返回登录</el-button>
    </el-form>
  </div>
</template>

<script>
import { validUsername } from '@/utils/validate'
import { sendPhoneMsg, updatePassword } from '@/api/user'
import { mapActions } from 'vuex'
import { Message } from 'element-ui'

export default {
  name: 'Login',
  data() {
    // 密码强度验证（必须包含大写字母、小写字母、数字，8位以上）
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('密码不能为空'))
      }
      // if (value.length < 8) {
      //   return callback(new Error('密码长度不能少于8位'))
      // }
      // if (!/(?=.*[a-z])/.test(value)) {
      //   return callback(new Error('密码必须包含小写字母'))
      // }
      // if (!/(?=.*[A-Z])/.test(value)) {
      //   return callback(new Error('密码必须包含大写字母'))
      // }
      // if (!/(?=.*\d)/.test(value)) {
      //   return callback(new Error('密码必须包含数字'))
      // }
      callback()
    }
    
    // 确认密码验证
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.recoverForm.newPassword) {
        callback(new Error('两次输入的密码不一致!'))
      } else {
        callback()
      }
    }
    
    // 手机号验证
    const validatePhone = (rule, value, callback) => {
      if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }

    return {
      loginForm: {
        name: '',
        password: '',
        verifyCode: ''
      },
      loginRules: {
        name: [{ required: true, message: '请填写用户名', trigger: 'blur' }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
      },
      recoverForm: {
        phone: '',
        code: '',
        newPassword: '',
        confirmPassword: ''
      },
      recoverRules: {
        phone: [{ required: true, trigger: 'blur', validator: validatePhone }],
        code: [{ required: true, message: '请填写验证码', trigger: 'blur' }],
        newPassword: [{ required: true, trigger: 'blur', validator: validatePassword }],
        confirmPassword: [{ required: true, trigger: 'blur', validator: validateConfirmPassword }]
      },
      passwordType: 'password',
      redirect: undefined,
      otherQuery: {},
      fcode: '',
      showRecover: false,
      countdown: 0,
      timer: ''
    }
  },
  created() {
    this.refreshCode()
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  },
  methods: {
    ...mapActions(['Login', 'Logout']),
    checkCapslock(e) {
      const { key } = e
      this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
    },
    // 获取验证码
    refreshCode() {
      if(process.env.NODE_ENV === "development"){
        this.fcode = "/admin/system/verifyCode?r=" + Math.random();
      }else{
        this.fcode = "/api/admin/system/verifyCode?r=" + Math.random();
      }
    },
    // 发送短信验证码
    sendSmsCode() {
      this.$refs.recoverForm.validateField('phone', (error) => {
        if (!error) {
          console.log(error);
          // 这里调用发送验证码的API
        sendPhoneMsg(this.recoverForm.phone)
            .then((res) => {
              Message.success('验证码已发送，请注意查收')
              this.countdown = 120
              this.timer = setInterval(() => {
              if (this.countdown > 0) {
              this.countdown--
              } else {
                clearInterval(this.timer)
              }
            }, 1000)
          })
        }
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '正在登陆中，请稍后...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          this.$store.dispatch('user/login', this.loginForm)
            .then((res) => {
              loading.close()
              if (!res.success) {
                // 登陆失败，回传提示信息
                Message.error(res.message)
                this.refreshCode()
                return;
              }
              this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
            })
        }
      })
    },
    handleRecover() {
      this.$refs.recoverForm.validate(valid => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '正在处理，请稍后...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          debugger;
          updatePassword(this.recoverForm).then((rsp) => {
            setTimeout(() => {
            loading.close()
            Message.success('密码重置成功，请重新登录')
            this.showRecover = false
            this.$refs.recoverForm.resetFields()
          }, 1500)
          })
          // 这里调用找回密码的API
          // 模拟API调用
          
        }
      })
    }
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg:#283443;
$light_gray:#fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
  
  .img-code {
    display: flex;
    position: relative;
    .el-form-item {
      width: 70%;
    }
    .verifyCode-img {
      position: absolute;
      right: 0;top: 3px;
      margin: auto;
      height: 45px;
      cursor: pointer;
    }
  }
  
  .send-code-btn {
    position: absolute;
    right: 0;
    top: 0;
    height: 100%;
    width: 120px;
    padding: 12px;
  }
}
</style>

<style lang="scss" scoped>
$bg:#2d3a4b;
$dark_gray:#889aa4;
$light_gray:#eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      cursor: pointer;
      color: #409EFF;
      
      &:hover {
        text-decoration: underline;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 10px auto;
      text-align: center;
      font-weight: bold;
      + p {
        text-align: center;
        color: $light_gray;
        margin: 0px auto 40px auto;
      }
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }

  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }
}
</style>